package com.esunrising.esungsc.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.esunrising.esungsc.common.utils.ESUNGSCUtil;
import com.esunrising.esungsc.common.utils.HttpUtil;
import com.esunrising.esungsc.config.GSCAPIConfig;
import com.esunrising.esungsc.dao.CustomItemCategoryDao;
import com.esunrising.esungsc.entity.ApiHsdw;
import com.esunrising.esungsc.entity.TApiXmlb;
import com.esunrising.esungsc.service.CustomItemCategoryService;
import com.esunrising.esungsc.service.GSCService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.*;

@Service
@Slf4j
public class CustomItemCategoryServiceImpl extends BaseServiceImpl<CustomItemCategoryDao, TApiXmlb> implements CustomItemCategoryService {

    @Resource
    private CustomItemCategoryDao dao;

    @Resource
    private GSCAPIConfig gscapiConfig;
    @Autowired
    private RestTemplate restTemplate;

    @Resource
    private GSCService gscService;

    @Resource
    private CustomItemCategoryService customItemCategoryService;

    @Override
    public List<TApiXmlb> getCustomItemCategoryResult(String hszzid, String year, String dwbh, String orgCode) {

        String orgId = "";
        String ledger = "";
        String type = "pz-test";

        String baseUrl = gscapiConfig.getBaseUrl();
        String s = gscapiConfig.getApis().get("getBFCustomItemCategory");
        String url = baseUrl + s;

        //添加query参数
        String queryParam = HttpUtil.putQueryParam(url, null);
        //添加请求头参数
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.addAll(new LinkedMultiValueMap<>(gscapiConfig.getRequestHeaders()));

        //添加body请求体参数
        HashMap<String, Object> bodyhttp = new HashMap<>();
        bodyhttp.put("hszzid", hszzid);
        bodyhttp.put("year", year);

        //组织参数
        HttpEntity<HashMap<String, Object>> httpEntity = new HttpEntity<>(bodyhttp, httpHeaders);

        //发送请求
        ResponseEntity<String > response = restTemplate.exchange(queryParam, HttpMethod.POST, httpEntity, String.class);

        String msg = "";
        if (response.getStatusCodeValue() == 200){
            String responseBody = response.getBody();
            System.out.println("是否从文档中取出数据："+response);

            msg = "获取成功";
            //记录日志
            gscService.saveLog(dwbh,orgId,orgCode,ledger,type,msg);
            //更新调用时间记录
            gscService.updateSyncTime(dwbh,orgId,orgCode,ledger,type, LocalDateTime.now());
            return parsegetBFCustomItemCategory(responseBody);
        }else {
            msg = "接口取数失败";
            //记录日志
            gscService.saveLog(dwbh,orgId,orgCode,ledger,type,msg);

            System.out.println(response.getStatusCode());
            System.out.println(response.getStatusCodeValue());
            System.out.println(response.getHeaders());
            System.out.println(response.getBody());

            return null;
        }
    }

    @Override
    public void saveTApiXmlb(List<TApiXmlb> tApiXmlbList) {
        for (TApiXmlb tApiXmlb : tApiXmlbList) {
            System.out.println("--单个tapixmlb--"+tApiXmlb);
            customItemCategoryService.syncSave(tApiXmlb);
        }
    }

    @Override
    public void syncSave(TApiXmlb tApiXmlb) {
        //如果存在就删除
        Optional<TApiXmlb> byId = dao.findById(tApiXmlb.getId());
        byId.ifPresent( doc ->{
            dao.deleteById(doc.getId());
        });
        //保存数据；
        super.save(tApiXmlb);
    }

    public TApiXmlb findById(String id) {
        Optional<TApiXmlb> byId = dao.findById(id);
        return byId.orElse(null);
    }

    public  List<TApiXmlb> parsegetBFCustomItemCategory(String responseBody) {
        //解析json字符串
        JSONObject jsonObject = JSON.parseObject(responseBody);
        Boolean result = jsonObject.getBoolean("result");
        String code = jsonObject.getString("code");
        if (result){
            log.info("请求核算项目类别数据成功");
            JSONArray value = jsonObject.getJSONArray("value");
            List<TApiXmlb> tApiXmlbs = new ArrayList<>();
            int size = value.size();
            for (int i = 0; i < size; i++) {
                JSONObject element = value.getJSONObject(i);
                TApiXmlb tApiXmlb = ESUNGSCUtil.jsonObject2ApiXmlb(element);
                //加入到tApiXmlb中
                tApiXmlbs.add(tApiXmlb);
            }
            return tApiXmlbs;
        }else {
            log.error("请求核算项目类别数据失败");
            return null;
        }

    }
}
